package com.vshop.controller.externalInterface;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.external.aheadfinish.request.RequestAheadFinishOrder;
import com.vshop.entity.external.aheadfinish.request.RequestAheadFinishOrderData;
import com.vshop.entity.external.aheadfinish.response.ResponseAheadFinishOrder;
import com.vshop.entity.external.aheadfinish.response.ResponseAheadFinishOrderData;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.requestinterface.Constant;
import com.vshop.entity.requestinterface.aheadfinish.request.RequestAheadFinishNew;
import com.vshop.entity.requestinterface.aheadfinish.response.ResponseAheadFinishNew;
import com.vshop.service.PartnerInfoService;
import com.vshop.service.SequenceService;
import com.vshop.utils.HttpUtil;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 提前结束套餐订单
 * 接入方可以通过调用该接口，查询某个设备信息，包括设备的基本信息、设备当前订购的套餐信息等
 * <p>
 * 此接口的意义在于查询到设备如果正在使用期内：
 * 提示用户"原有订单有关闭风险"，如果用户确认，便触发关闭正在使用的订单(即提前结束套餐订单)
 *
 * @author lm
 * @date 2019/09/17
 */
@RestController
@Api(description = "提前结束套餐订单")
@Slf4j
public class AheadFinishOrderController {
    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private PartnerInfoService partnerInfoService;

    /**
     * 直接请求网关xml接口的地址
     */
    @Value("${iot.requestURI}")
    private String requestURI;

    @CrossOrigin
    @PostMapping(value = "aheadFinishOrder", produces = "application/json;charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "提前结束套餐订单 ", response = ResponseAheadFinishOrder.class)
    public String aheadFinishOrder(@ApiParam @RequestBody RequestAheadFinishOrder request) {

        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();

        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());

        //3,定义要回复的内容
        String jsonString;

        ExceptionRequest utils = new ExceptionRequest();
        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("前端请求报文是：" + requestStr);
            RequestAheadFinishOrder requestPackage = JSONArray.parseObject(requestStr, RequestAheadFinishOrder.class);
            String requestSign = requestPackage.getSign();

            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                RequestAheadFinishOrderData requestData = requestPackage.getData();
                if (requestData == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {

                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String secret = partnerInfoService.getSecretByPartnerCode(partnerCode);
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String version = requestData.getVersion();

                    if (StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || StringUtils.isBlank(version) || requestData.getTradeData() == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {

                        String orderId = requestData.getTradeData().getOrderId();

                        if (StringUtils.isBlank(orderId)) {
                            log.info("请求报文不合法:tradeData参数不合法");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            String str = JSON.toJSONString(requestData);
                            String sign = utils.calculateSignature(str);
                            log.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                                return jsonString;

                            } else {
                                RequestAheadFinishNew aheadFinish = new RequestAheadFinishNew();
                                aheadFinish.setOrderId(orderId);
                                aheadFinish.setDeviceType("4");
                                aheadFinish.setAheadFinishCause("周期未结束需开启新的订单");
                                aheadFinish.setPartnerCode(partnerCode);
                                aheadFinish.setSecret(secret);

                                //组装需要的json去请求报文
                                String requestInterface = JSON.toJSONString(aheadFinish);
                                log.info("请求报文：" + requestInterface);
                                String url = requestURI + Constant.iot_aheadFinishDeviceOrder;
                                // 发送post请求，并接收返回结果
                                String returnStr = HttpUtil.httpPost(url, requestInterface);
                                log.info("北京响应：" + returnStr);
                                ResponseAheadFinishNew response = JSONArray.parseObject(returnStr, ResponseAheadFinishNew.class);

                                if (response != null) {

                                    if (true == Constant.RET_CODE_0000.equalsIgnoreCase(response.getRetCode())) {

                                        if (true == Constant.RET_CODE_0000.equalsIgnoreCase(response.getError())) {

                                            ResponseAheadFinishOrderData data = new ResponseAheadFinishOrderData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(tradeTime);
                                            data.setRetCode(response.getRetCode());
                                            data.setRetMsg(response.getErrorMsg());

                                            ResponseAheadFinishOrder res = new ResponseAheadFinishOrder();
                                            res.setData(data);
                                            res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                            jsonString = JSON.toJSONString(res);
                                            log.info("响应报文：" + jsonString);
                                            return jsonString;


                                        } else {

                                            ResponseAheadFinishOrderData data = new ResponseAheadFinishOrderData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(tradeTime);
                                            data.setRetCode(response.getError());
                                            data.setRetMsg(response.getErrorMsg());

                                            ResponseAheadFinishOrder res = new ResponseAheadFinishOrder();
                                            res.setData(data);
                                            res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                            jsonString = JSON.toJSONString(res);
                                            log.info("响应报文：" + jsonString);
                                            return jsonString;
                                        }

                                    } else {
                                        ResponseAheadFinishOrderData data = new ResponseAheadFinishOrderData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(tradeTime);
                                        data.setRetCode(response.getRetCode());
                                        data.setRetMsg(response.getResultInfo());

                                        ResponseAheadFinishOrder res = new ResponseAheadFinishOrder();
                                        res.setData(data);
                                        res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                        jsonString = JSON.toJSONString(res);
                                        log.info("响应报文：" + jsonString);
                                        return jsonString;
                                    }


                                } else {
                                    ResponseAheadFinishOrderData data = new ResponseAheadFinishOrderData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(tradeTime);
                                    data.setRetCode("9999");
                                    data.setRetMsg("接口响应出现异常");

                                    ResponseAheadFinishOrder res = new ResponseAheadFinishOrder();
                                    res.setData(data);
                                    res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                    jsonString = JSON.toJSONString(res);
                                    log.info("响应报文：" + jsonString);
                                    return jsonString;
                                }


                            }
                        }
                    }
                }
            }

        }

    }
}
